package com.redhat.auth.web.role;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.redhat.auth.application.RoleApplication;
import com.redhat.auth.domain.Role;
import com.redhat.auth.domain.Role.Status;
import com.redhat.redwork.coc.RedworkAction;
import com.redhat.redwork.coc.RedworkActionSupport;

/**
 * 角色管理
 *<br />
 * @author vakin.Jiang
 *2010-4-26
 */
public class RoleAction extends RedworkActionSupport implements RedworkAction {

	private static final long serialVersionUID = 1L;
	
	private static final Logger	logger  = LoggerFactory.getLogger(RoleAction.class);
	
	@Autowired
	private RoleApplication roleAppliaction;
	
	private String id;
	private Role role;
	
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}
	
	
	/**
	 * 新增/修改保存事件
	 * @return
	 */
	public String save(){

		//TODO exception i18n
		if(role.isNew()){
			role.setStatus(Status.ENABLED);
			role.setVersion(0);
			roleAppliaction.createRole(role);
		}else
			roleAppliaction.updateRole(role);
		
		return JSON;
	}
	
	/**
	 * 编辑按钮事件（读取记录字段，填充至编辑页面）
	 * @return
	 */
	public String edit(){
		role = roleAppliaction.getRoleById(Long.parseLong(id));
		return "edit";
	}
	
	
	/**
	 * 权限分配预处理（读取，跳转）
	 * @return
	 */
	public String preAddpermissions(){
		ServletActionContext.getRequest().setAttribute("id", id);
		return "addpermissions";
	}
	
	/**
	 * 权限分配事件
	 * @return
	 */
	public String addPermissions(){
		String functionEntitys =ServletActionContext.getRequest().getParameter("funids");
		String[] funIds = functionEntitys.split(",");
		
		if(funIds==null || funIds.length==0){
			addActionError("<script>alert('传入数据为空');</script>");
		}
		try {
			roleAppliaction.addPermissions(Long.parseLong(id), funIds);
		} catch (Exception e) {
			logger.error("",e);
			e.printStackTrace();
		}
		return JSON;
	}


	/**
	 * 设置状态
	 * @return
	 */
	public String setStatus(){
	    if(StringUtils.isNotBlank(id)){
	    	ServletActionContext.getRequest().setAttribute("id", id);
	    	return "setStatus";
	    }
		roleAppliaction.changeStatus(role.getId(),role.getStatus());
		return JSON;
	}
}
